package com.lfg.leetcode.leetcode200;

import java.util.Stack;

public class No224calculate {

    public static void main(String[] args) {
        int ret = calculate2("  5+3-4-(1+2-7+(10-1+3+5+(3-0+(8-(3+(8-(10-(6-10-8-7+(0+0+7)-10+5-3-2+(9+0+(7+(2-(2-(9)-2+5+4+2+(2+9+1+5+5-8-9-2-9+1+0)-(5-(9)-(0-(7+9)+(10+(6-4+6))+0-2+(10+7+(8+(7-(8-(3)+(2)+(10-6+10-(2)-7-(2)+(3+(8))+(1-3-8)+6-(4+1)+(6))+6-(1)-(10+(4)+(8)+(5+(0))+(3-(6))-(9)-(4)+(2))))))-1)))+(9+6)+(0))))+3-(1))+(7)))))))) ");
//        int ret = calculate2("1+1");
        System.out.println(ret);
    }

    public static int calculate2(String s) {
        int ret = 0;
        int opr = 1;
        int length = s.length();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                continue;
            }
            if (c >= '0' && c <= '9') {
                int num = c - '0';
                while (++i < length) {
                    c = s.charAt(i);
                    if (c < '0' || c > '9') {
                        break;
                    }
                    num = 10 * num + (c - '0');
                }
                i--;
                ret += opr * num;
            } else if (c == '(') {
                stack.push(ret);
                stack.push(opr);
                ret = 0;
                opr = 1;
            } else if (c == ')') {
                ret *= stack.pop();
                ret += stack.pop();
            } else if (c == '+') {
                opr = 1;
            } else if (c == '-') {
                opr = -1;
            }
        }

        return ret;
    }

    public static int calculate(String s) {
        int res = 0, sign = 1, n = s.length();
        Stack<Integer> st = new Stack<>();
        for (int i = 0; i < n; ++i) {
            char c = s.charAt(i);
            if (c >= '0') {
                int num = 0;
                while (i < n && s.charAt(i) >= '0') {
                    num = 10 * num + s.charAt(i++) - '0';
                }
                res += sign * num;
                --i;
            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else if (c == '(') {
                st.push(res);
                st.push(sign);
                res = 0;
                sign = 1;
            } else if (c == ')') {
                res *= st.pop();
                res += st.pop();
            }
        }
        return res;
    }
}
